/*
 * @Descripttion: 
 * @Author: voanit
 * @Date: 2022-06-07 17:51:53
 * @LastEditors: voanit
 * @LastEditTime: 2022-06-08 16:41:33
 */
import ArticleItem from '../ArticleItem/ArticleItem'
import { useEffect, useLayoutEffect } from 'react'
import styles from './index.module.scss'
import { useDispatch, useSelector } from 'react-redux'
import { getArticleList, getNewArticleList } from '@/store/actions/article'
import { RootState } from '@/types/store'
import { InfiniteScroll, PullToRefresh } from 'antd-mobile'
// import { useHistory } from 'react-router-dom'
import history from '@/utils/history'
type Props = {
  channelId: number
}
const ArticleList = ({ channelId }: Props) => {
  // console.log(channelId, 333444);

  const dispatch = useDispatch()
  // useEffect(() => {
  //   // dispatch(getArticleList(Number(channelId), Date.now() + ''))
  //   // console.log(channelId, 22);
  // }, [channelId, dispatch])

  const channelArticles = useSelector((state: RootState) => state.article)
  const { articles, timestamp } = channelArticles[channelId] || { articles: [], timestamp: Date.now() }
  // console.log(articles, 223);
  // 必须返回一个Promise对象
  const hasMore = timestamp !== null
  const loadMore = async () => {
    // console.log('加载更多数据')
    await dispatch(getArticleList(channelId, timestamp || Date.now() + ''))
  }

  /* 下拉 */
  const onRefresh = async () => {
    // 重置当前频道的数据，重新加载第一页的数据
    await dispatch(getNewArticleList(channelId, Date.now() + ''))
    // console.log(channelArticles, 99);
  }

  // const history = useHistory()

  return (
    <div className={styles.root}>
      {/* 文章列表中的每一项 */}
      <PullToRefresh onRefresh={onRefresh}>
        {articles.length > 0 && articles.map((item) => (
          <div key={item.art_id} className="article-item" onClick={() => history.push(`/article/${item.art_id}`)}>
            <ArticleItem article={item} />
          </div>
        ))}

        {/* 无限加载组件 */}
        <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
      </PullToRefresh>
    </div >
  )
}

export default ArticleList